
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>

#include "threadpool.h"

#define PORT 8080

void working(void* arg);
void acceptConn(void* arg);

struct PoolInfo{
    struct ThreadPool* p;
    int fd;
};

struct SockInfo{
    struct sockaddr_in addr;
    int fd;
};

int main()
{
    int fd = 0;
    struct sockaddr_in saddr;

    //1. 创建通信套接字
    if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        return -1;
    }

    //2. 绑定端口
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(PORT);
    saddr.sin_addr.s_addr = INADDR_ANY;

    int ret = bind(fd,(struct sockaddr*)&saddr, sizeof(saddr));
    if(-1 == ret)
    {
        perror("bind");
        return -1;
    }

    //3. 设置监听
    ret = listen(fd, 128);
    if(-1 == ret)
    {
        perror("listen");
        return -1;
    }

    // 创建线程池
    struct ThreadPool* pool = threadPoolCreate(3, 10, 100);
    struct PoolInfo* poolinfo = (struct PoolInfo*)malloc(sizeof(struct PoolInfo));
    poolinfo->p = pool;
    poolinfo->fd = fd;
    threadPoolAdd(pool, acceptConn, poolinfo);

    pthread_exit(NULL);

    return 0;
}

void acceptConn(void* arg)
{
    struct PoolInfo* poolinfo = (struct PoolInfo*)arg;
    int caddrlen = sizeof(struct sockaddr_in);
    while(1)
    {
        struct SockInfo* sockinfo;
        sockinfo = (struct SockInfo*)malloc(sizeof(struct SockInfo));
        sockinfo->fd = accept(poolinfo->fd, (struct sockaddr*)&sockinfo->addr, &caddrlen);
        if(-1 == sockinfo->fd)
        {
            perror("accept");
            break;
        }

        // 添加线程任务
        threadPoolAdd(poolinfo->p, working, sockinfo);

    }

    // 关闭通信描述符
    close(poolinfo->fd);
}

void working(void* arg)
{
    struct SockInfo* pinfo = (struct SockInfo*)arg;

    //打印客户端信息
    char ip[32] = {0};
    printf("客户端IP: %s, 端口: %d\n",
         inet_ntop(AF_INET, &pinfo->addr.sin_addr.s_addr, ip, sizeof(ip)),
          ntohs(pinfo->addr.sin_port)
        );

     //5. 通信
    while(1)
    {
        //接收信息
        char buff[1024];
        int len = recv(pinfo->fd, buff, sizeof(buff), 0);
        if(len > 0)
        {
            printf("client say: %s....\n", buff);
            //发送信息
            send(pinfo->fd, buff, len, 0);
        }

        else if(0 == len)
        {
            printf("客户端已经断开了连接....\n");
            break;
        }
        
        else
        {
            perror("recv");
            break;
        }
    }
    //关闭文件描述符
    close(pinfo->fd);
}
